import React from 'react';
import { Modal, Spin, Card, Button, Switch, Select, Input, Tooltip, Icon, Tabs, notification } from 'antd';
import * as actions from './../../../actions/backstage/carouselAction';
import TableView from './../TableView';
const { Option, OptGroup } = Select;
const TextArea = Input.TextArea;
const TabPane = Tabs.TabPane;

class carouselManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            findProduct: GLOBAL.baseURL + "/webAPI/product/findProducts",
            updateCarouselLoading: false,
            updateLoading: false,
            addCarouselImg: false,
            productList: false,
            totalPageNum: 0,
            serverData: [],
            requestData: {},
            productListData: [],
            tempProductData: null,
            productData: null,
            isHaveProduct: false,
            visibleDeleteAlert: false,
            visibleStatusAlert: false,
            searchObject: {},
            delId: '',
            delPic: '',
            txtStatus: '',
            articleFlap: 'add',
            btnSaveDisabled: true,
            modalInfo: '你确定想改变为: 禁用？',
            carouselWidth: 1920,
            carouselHeight: 350
        }
    }
    componentDidMount(){
        this.onRefreshData();
    }
    onRefreshData(){
        actions.findCarousels(this, {whichType: false});
    }
    searchStatus(val){
        if(val == ""){
          actions.findCarousels(this, {whichType: false});
        }else {
          actions.findCarousels(this, {whichType: false, status: val});
        }
    }
    onTypeChange(val){
        if(val == -1){
          delete this.state.searchObject.type;
          delete this.state.searchObject.status;
        }else {
          this.state.searchObject.type = val;
          this.state.searchObject.status = "active"
        }
        this.refs["productListView"].refreshData();
    }
    isHaveProduct(val){
        if(val == true){
            if(this.state.productData != null){
                this.state.requestData.pId = this.state.productData.id;
            }
        }else if(val == false){
            delete this.state.requestData.pId;
        }
        this.setState({isHaveProduct: val});
    }
    totalPageNum(num) {
        this.setState({
            totalPageNum: num
        })
    }
    getServiceData(data) {
        this.setState({
            productListData: data,
            updateLoading: false
        });
    }
    addCarouselImg(){
        this.state.fileVerify = false;
        this.setState({addCarouselImg: true, articleFlap: 'add', requestData: {}, btnSaveDisabled: false});
    }
    btnShowCarousel(val){
        this.setState({addCarouselImg: val});
        if(val == false){
            $("#carouselPic").val('');
            document.getElementById("imgPreview").src = "/src/styles/images/defaultCarousel.jpg";
            this.setState({
              tempProductData: null,
              productData: null,
              isHaveProduct: false
            });
        }
    }
    btnShowProductList(val){
        var that = this;
        this.setState({productList: val});
        if(val == true){
          that.setState({updateLoading: true});
          setInterval(function(){
            window.onresize();
          }, 300);
          setTimeout(function(){
            that.refs["productListView"].refreshData();
            window.onresize();
          }, 800);
        }
    }
    //尺寸：1920 x 350（px）
    getImgSize(imgFile){
        var that = this;
        var reader = new FileReader();
        reader.readAsDataURL(imgFile.files[0])
        reader.onload = function (e) {
           var image = new Image();
           image.src = e.target.result;
           image.onload= () => {
             // if(image.naturalWidth != that.state.carouselWidth || image.naturalHeight != that.state.carouselHeight){
             //     notification.warn({
             //         placement: 'bottomRight',
             //         message: '提示：',
             //         description: '图片尺寸: 必须是 ' + that.state.carouselWidth + ' * ' + that.state.carouselHeight + ' 像素。',
             //         style: {
             //           borderLeft: '4px solid rgb(255, 191, 0)'
             //         }
             //     });
             //     that.state.fileVerify = false;
             //     document.getElementById("imgPreview").src = "/src/styles/images/defaultCarousel.jpg";
             // }else{
             //     that.state.fileVerify = true;
             //     document.getElementById("imgPreview").src = e.target.result;
             // }
               that.state.fileVerify = true;
               document.getElementById("imgPreview").src = e.target.result;
   	      }
       }
    }
    verifyMsgAndImage(){
        if($("#carouselPic")[0].files.length >= 1){
            var file = $("#carouselPic")[0].files[0];
            if (!(file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/bmp')) {
              notification.warn({
                  placement: 'bottomRight',
                  message: '提示：',
                  description: '你只能选择 JPG, PNG, GIF 和 BMP。',
                  style: {
                    borderLeft: '4px solid rgb(255, 191, 0)'
                  }
              });
              this.state.fileVerify = false;
              document.getElementById("imgPreview").src = "/src/styles/images/defaultCarousel.jpg";
              return;
            }
            const isLt2M = file.size < 819200; // 大小：800k
            if (!isLt2M) {
              notification.warn({
                  placement: 'bottomRight',
                  message: '提示：',
                  description: '图片大小小于 800 KB。',
                  style: {
                    borderLeft: '4px solid rgb(255, 191, 0)'
                  }
              });
              this.state.fileVerify = false;
              document.getElementById("imgPreview").src = "/src/styles/images/defaultCarousel.jpg";
              return;
            }
            this.getImgSize($("#carouselPic")[0]);
        }
    }
    btnSaveCarouselImg(){
        debugger;
        if(this.state.articleFlap == 'add'){
            if($("#carouselPic")[0].files.length >= 1){
                if(this.state.fileVerify == true){
                    if(this.state.isHaveProduct == true && this.state.productData != null){
                      this.state.requestData.pId = this.state.productData.id;
                    }else {
                      delete this.state.requestData.productId;
                    }
                    this.state.requestData.whichType = false;
                    actions.addOrEditCarousel(this, this.state.requestData, "add");
                }else{
                    notification.warn({
                        placement: 'bottomRight',
                        message: '提示',
                        description: '文件类型, 尺寸大小(' + this.state.carouselWidth + ' * ' + this.state.carouselHeight + ') 错误。',
                        style: {
                          borderLeft: '4px solid rgb(255, 191, 0)'
                        }
                    });
                }
            }else{
                notification.warn({
                    placement: 'bottomRight',
                    message: '提示：',
                    description: '轮播图 必须选择。',
                    style: {
                      borderLeft: '4px solid rgb(255, 191, 0)'
                    }
                });
            }
        }else {
            if($("#carouselPic")[0].files.length >= 1){
                if(this.state.fileVerify == true){
                    if(this.state.isHaveProduct == true && this.state.productData != null){
                      this.state.requestData.pId = this.state.productData.id;
                    }else {
                      delete this.state.requestData.productId;
                    }
                    actions.addOrEditCarousel(this, this.state.requestData, "edite");
                }else{
                    notification.warn({
                        placement: 'bottomRight',
                        message: '提示：',
                        description: '文件类型, 尺寸大小(' + this.state.carouselWidth + ' * ' + this.state.carouselHeight + ') 错误。',
                        style: {
                          borderLeft: '4px solid rgb(255, 191, 0)'
                        }
                    });
                }
            }else{
                if(this.state.isHaveProduct == true && this.state.productData != null){
                  this.state.requestData.pId = this.state.productData.id;
                }else {
                  delete this.state.requestData.productId;
                }
                actions.addOrEditCarousel(this, this.state.requestData, "edite");
            }
        }
    }
    onChangeDescribe(val){
        this.setState({
          requestData: {
              ...this.state.requestData,
              describe: val.target.value
          }
        });
    }
    onImgLoad(e){
        $(e.currentTarget).css("backgroundImage", "none");
    }
    selectProduct(item){
        this.setState({tempProductData: item});
    }
    btnConfirmProduct(){
        this.setState({productData: this.state.tempProductData, productList: false});
    }
    deleteCarousel(id, pic){
        this.setState({
          visibleDeleteAlert: true,
          delId: id,
          delPic: pic
        });
    }
    onConfirmDelete(){
        actions.removeCarousel(this, {
          id: this.state.delId,
          pic: this.state.delPic
        });
    }
    editCarousel(item){
        var that = this;
        this.setState({requestData: item, articleFlap:'edite', addCarouselImg: true, btnSaveDisabled: true});
        setTimeout(function(){
            document.getElementById("imgPreview").src = "http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.pic;
            if(item.productId != undefined){
                actions.findProductDetial(that, item.productId);
            }else{
                that.setState({btnSaveDisabled: false});
            }
        }, 1000);
    }
    changeStatus(cId, status){
        if(status == "inactive"){
            this.setState({
              visibleStatusAlert: true,
              delId: cId,
              txtStatus: status,
              modalInfo: <span>你确定想改变为 <span style={{color:'#da1010'}}>禁用</span> ？</span>
            });
        }else {
            this.setState({
              visibleStatusAlert: true,
              delId: cId,
              txtStatus: status,
              modalInfo: <span>你确定想改变为 <span style={{color:'#148dd6'}}>启用</span> ？</span>
            });
        }
    }
    onConfirmStatus(){
        actions.changeStatus(this, {
          cId: this.state.delId,
          status: this.state.txtStatus
        });
    }
    renderItem(item, index) {
        var imgCoverPicture = null;
        if(item.productPic != undefined){
            imgCoverPicture = <div className="divUserHead">
              <img className="imgCoverPicture" src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.productPic} onLoad={this.onImgLoad.bind(this)}/>
            </div>
        }else{
            imgCoverPicture = <div className="divUserHead">
              <img className="imgCoverPicture" src="/src/styles/images/listDefault_Large.png"/>
            </div>
        }
        var divSelected = null;
        if(this.state.tempProductData != null){
            if(item.id == this.state.tempProductData.id){
                divSelected = <div className="divSelected" style={{display: 'block'}}></div>
            }else{
                divSelected = <div className="divSelected"></div>
            }
        }
        return (
            <Card key={index} onClick={this.selectProduct.bind(this, item)} className="divItemLineMini" style={{width: '316px', marginBottom: '16px'}}>
                {imgCoverPicture}
                <div className="userInfo">
                    <div className="divArticleTitle1" title={((item.productName == undefined)?"":item.productName)}>
                        <span>{'商品名：' + ((item.productName == undefined)?"":item.productName) + ((item.brandName == undefined)?"":"（" + item.brandName + "）")}</span>
                    </div>
                    <div className="divArticleContent2" title={((item.reminder == undefined)?"":item.reminder)}>
                        <span>{'温馨提示：' + ((item.reminder == undefined)?"":item.reminder)}</span>
                    </div>
                    <div className="pOverview">
                        <span style={{color: '#fff'}}>
                          <Icon type="eye" className="iconEye" title="浏览"/>{item.browseNumbers}
                          <Icon type="message" className="iconEye" title="评论"/>{item.commentIds.length}
                        </span>
                    </div>
                    <div className="divContent">
                        <span>{'创建：' + ((item.commitTime == undefined)?"":new Date(item.commitTime).Format("yyyy-MM-dd"))}</span>
                        <span>{((item.updateTime == undefined)?"":'，修改：' + new Date(item.updateTime).Format("yyyy-MM-dd"))}</span>
                    </div>
                    {divSelected}
                </div>
            </Card>
        );
    }
    renderImageItem(item, index){
        // unlock、lock
        var btnStatus = null;
        if(item.status == 'inactive'){
            btnStatus = <Button type="primary" shape="circle" title="状态: 禁用" icon="lock" style={{marginRight: '5px'}} onClick={this.changeStatus.bind(this, item.id, 'active')}/>
        }else{
            btnStatus = <Button type="primary" shape="circle" title="状态: 启用" icon="unlock" style={{marginRight: '5px'}} onClick={this.changeStatus.bind(this, item.id, 'inactive')}/>
        }
        return <div key={index} className="divCarouselItem">
            <div className="divOperate">
                {btnStatus}
                <Button type="danger" shape="circle" icon="delete" onClick={this.deleteCarousel.bind(this, item.id, item.pic)}/>
            </div>
            <img src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.pic} onClick={this.editCarousel.bind(this, item)} onLoad={this.onImgLoad.bind(this)}/>
            <div className="divDescribe" title={item.describe} onClick={this.editCarousel.bind(this, item)}>
              {"创建时间: " + new Date(item.createTime).Format("yyyy-MM-dd hh:mm") + ((item.updateTime == undefined)?"": ", 修改时间: " + new Date(item.updateTime).Format("yyyy-MM-dd hh:mm"))}<br />
              {"描述: " + ((item.describe == undefined)?"无":item.describe)}
            </div>
        </div>
    }
    render() {
      var serverProductList = null; var productInfo = null;
      if(this.state.productListData.length != 0){
          serverProductList = <div className="divFlexListMini">
            {
                this.state.productListData.map((item, index) => {
                    return this.renderItem(item, index);
                })
            }
          </div>
      }else{
          serverProductList = <div className="divEmptyDataMini">对不起，没有相关商品。</div>
      }
      if(this.state.isHaveProduct == true){
          if(this.state.productData == null){
              var productInfo = <div style={{marginLeft: '4px',minHeight: '52px'}}>
                  <Tooltip placement="bottomRight" title="选择商品">
                      <Button icon="plus-circle-o" type="primary" className="btnClose btnGreen" onClick={this.btnShowProductList.bind(this, true)}>选择商品</Button>
                  </Tooltip>
              </div>
          }else{
              var imgCoverPicture = null; var item = this.state.productData;
              if(item.productPic != undefined){
                  imgCoverPicture = <div className="divUserHead">
                    <img className="imgCoverPicture" style={{width: '131px', border: '1px dotted #d8d8d8'}} src={"http://tinsley.oss-cn-shenzhen.aliyuncs.com/" + item.productPic} onLoad={this.onImgLoad.bind(this)}/>
                  </div>
              }else{
                  imgCoverPicture = <div className="divUserHead">
                    <img className="imgCoverPicture" style={{width: '131px', border: '1px dotted #d8d8d8'}} src="/src/styles/images/default.png"/>
                  </div>
              }
              var productInfo = <Card className="divItemLineMini" onClick={this.btnShowProductList.bind(this, true)} style={{width: '593px', marginTop: '6px', marginBottom: '6px', marginLeft: '7px'}}>
                  {imgCoverPicture}
                  <div className="userInfo" style={{marginTop: '-179px', marginLeft: '129px', backgroundColor: 'transparent'}}>
                      <div className="pOverview" style={{marginLeft: '-135px', marginTop: '2px', width: '129px', lineHeight: '25px', marginBottom: '17px', backgroundColor: 'rgba(185, 156, 255, 0.88)'}}>
                          <span style={{color: '#fff'}}>
                            <Icon type="eye" className="iconEye" style={{verticalAlign: 'text-top'}} title="浏览"/>{item.browseNumbers}
                            <Icon type="message" className="iconEye" style={{fontSize: '16px', verticalAlign: 'baseline'}} title="评论"/>{item.commentIds.length}
                          </span>
                      </div>
                      <div className="divArticleTitle1" style={{width: '436px', fontSize: '17px', fontWeight: 'bold'}} title={((item.productName == undefined)?"":item.productName) + ((item.brandName == undefined)?"":"（" + item.brandName + "）")}>
                          <span>{'商品名：' + ((item.productName == undefined)?"":item.productName) + ((item.brandName == undefined)?"":"（" + item.brandName + "）")}</span>
                      </div>
                      <div className="divArticleTitle1" style={{width: '436px', marginBottom: '7px', fontSize: '14px', color: '#b1b1b1', paddingLeft: '24px'}} title={((item.title == undefined)?"":item.title)}>
                          <span>{"标题：" + ((item.title == undefined)?"":item.title)}</span>
                      </div>
                      <div className="divArticleTitle1" style={{width: '436px', paddingLeft: '22px'}}>
                          <span>价格：</span>
                          <span style={{color: '#f95050', fontSize: '23px', marginRight: '5px'}}>
                            Rm
                            <span style={{fontSize: '18px'}}>{item.price}</span>
                          </span>
                          <span style={{textDecoration: 'line-through', fontSize: '13px', color: '#c7c7c7'}}>
                            Rm<span>{item.discountPrice}</span>
                          </span>
                      </div>
                      <div className="divArticleContent2" style={{width: '485px', paddingLeft: '22px', marginBottom: '18px'}} title={((item.reminder == undefined)?"":item.reminder)}>
                          <span>{'提示：' + ((item.reminder == undefined)?"":item.reminder)}</span>
                      </div>

                      <div className="divContent" style={{textAlign: 'right', width: '438px', color: '#b1b1b1'}}>
                          <span>{'创建：' + ((item.commitTime == undefined)?"":new Date(item.commitTime).Format("yyyy-MM-dd"))}</span>
                          <span>{'，修改：' + ((item.updateTime == undefined)?"":new Date(item.updateTime).Format("yyyy-MM-dd"))}</span>
                      </div>
                  </div>
              </Card>
          }
      }else if(this.state.isHaveProduct == false){
          var productInfo = <div className="divDisableAssociation">禁用商品关联</div>
      }

      var serverList = null;
      if(this.state.serverData.length != 0){
          serverList = <div style={{marginTop: '10px'}}>
            {
                this.state.serverData.map((item, index) => {
                    return this.renderImageItem(item, index);
                })
            }
          </div>
      }else{
          serverList = <div className="divEmptyData">对不起，没有可用数据。</div>
      }
      var btnAddCarouselImg = null;
      if(this.state.serverData.length < 9){
          btnAddCarouselImg = <span>
            <span style={{color: '#ec1e1e', fontSize: '14px'}}>轮播图最多 9 张，尺寸：{this.state.carouselWidth} * {this.state.carouselHeight}（像素）</span>
            <Button icon="plus-circle-o" type="primary" onClick={this.addCarouselImg.bind(this)}>添加轮播图</Button>
          </span>
      }else{
          btnAddCarouselImg = <span style={{color: '#ec1e1e', fontSize: '14px'}}>轮播图最多 9 张，尺寸：{this.state.carouselWidth} * {this.state.carouselHeight}（像素）。</span>
      }
      return (
          <div>
              <div className="divUpdateVideo">
                  <div style={{ display: 'inline-block', float: 'left'}}>
                    状态：<Select defaultValue="" style={{ width: 120 }} onChange={this.searchStatus.bind(this)}>
                      <Option value="">全部</Option>
                      <Option value="active">启用</Option>
                      <Option value="inactive">禁用</Option>
                    </Select>
                  </div>
                  {btnAddCarouselImg}
              </div>
              {serverList}
              <Modal
                  title="添加 轮播图"
                  visible={this.state.addCarouselImg}
                  wrapClassName="vertical-center-modal"
                  footer={null}
                  onCancel={this.btnShowCarousel.bind(this, false)}
                  width="auto"
                  maskClosable={false}
              >
                  <Spin spinning={this.state.updateCarouselLoading} tip="上传中，请稍候...">
                      <Tabs defaultActiveKey="1">
                        <TabPane tab="选择轮播图" key="1">
                            <div style={{height: '95px', marginBottom: '5px'}}>
                                <div style={{marginTop: '36px', marginLeft: '4px', display: 'inline-block',}}>
                                    <Tooltip placement="bottomRight" title="请选择轮播图">
                                        <input id="carouselPic" type="file" className="inputFile" onChange={this.verifyMsgAndImage.bind(this)} />
                                        <Button icon="picture" type="primary" className="btnClose btnGreen">选择轮播图</Button>
                                    </Tooltip>
                                </div>
                                <img id="imgPreview" style={{verticalAlign: 'middle', width: '424px', marginLeft: '27px', position: 'absolute', marginTop: '12px'}} src="/src/styles/images/defaultCarousel.jpg" title={"尺寸 (像素): " + this.state.carouselWidth + " * " + this.state.carouselHeight} />
                            </div>
                        </TabPane>
                      </Tabs>

                      <Tabs defaultActiveKey="1" tabBarExtraContent={<Switch checkedChildren={'开'} checked={this.state.isHaveProduct} unCheckedChildren={'关'} onChange={this.isHaveProduct.bind(this)}/>}>
                        <TabPane tab="选择商品" key="1">
                            {productInfo}
                        </TabPane>
                      </Tabs>
                      <Tabs defaultActiveKey="1">
                        <TabPane tab="描述信息" key="1">
                            <div className="divItem">
                                <Tooltip placement="bottomLeft" title="请输入描述 (必填)">
                                    <TextArea placeholder="请输入描述..." value={this.state.requestData.describe} style={{width: '600px',height: '90px', margin: '2px', resize: 'none'}} className="iptAuthor" type="textarea" rows={4} onChange={(val)=>this.onChangeDescribe(val)}/>
                                </Tooltip>
                            </div>
                        </TabPane>
                      </Tabs>

                      <div style={{textAlign: 'right', marginTop: '10px'}}>
                          <Button icon="close" style={{marginRight: '15px'}} onClick={this.btnShowCarousel.bind(this, false)}>取 消</Button>
                          <Tooltip placement="bottomRight" title="保存轮播图">
                              <Button icon="save" type="primary" className="btnClose" onClick={this.btnSaveCarouselImg.bind(this)} disabled={this.state.btnSaveDisabled}>保 存</Button>
                          </Tooltip>
                      </div>
                  </Spin>
              </Modal>
              <Modal
                  title="请选择商品"
                  visible={this.state.productList}
                  wrapClassName="center-modal"
                  footer={null}
                  onCancel={this.btnShowProductList.bind(this, false)}
                  width="100%"
                  maskClosable={false}
              >
                  <Spin spinning={this.state.updateLoading} wrapperClassName="spinUpdateLoading" tip="加载中...">
                      <div className="divType">
                          类型：<Select defaultValue="-1" style={{ minWidth: 120 }} onChange={this.onTypeChange.bind(this)} className="selectType">
                            <Option value="-1">全部</Option>
                            <Option value="1">推荐品牌</Option>
                            <Option value="2">女孩护肤</Option>
                            <Option value="3">面膜</Option>
                            <Option value="4">彩妆/口红</Option>
                            <Option value="5">个人护理</Option>
                            <Option value="6">保健产品</Option>
                          </Select>&nbsp;
                          状态：启用
                      </div>
                      {serverProductList}
                      <TableView ref="productListView" totalPageNum={this.totalPageNum.bind(this)}
                             isInternalRendering={false} getServiceData={this.getServiceData.bind(this)}
                             isService={true} searchObject={this.state.searchObject} pageNum={10}
                             url={this.state.findProduct} method="post" onPageSelected={()=>{this.setState({updateLoading: true})}}/>
                  </Spin>
                  <div style={{ position: 'fixed', right: '18px', bottom: '18px'}}>
                      <Button icon="close" style={{marginRight: '15px'}} onClick={this.btnShowProductList.bind(this, false)}>取 消</Button>
                      <Tooltip placement="bottomRight" title="选择商品">
                          <Button icon="check-circle-o" type="primary" className="btnClose" onClick={this.btnConfirmProduct.bind(this)}>确定商品</Button>
                      </Tooltip>
                  </div>
              </Modal>
              <Modal title="提示：" maskClosable={false} wrapClassName="vertical-center-modal" visible={this.state.visibleDeleteAlert} onOk={this.onConfirmDelete.bind(this)} onCancel={()=>{this.setState({visibleDeleteAlert: false})}}>
                  你确定要删除轮播图吗?
              </Modal>
              <Modal title="提示：" maskClosable={false} wrapClassName="vertical-center-modal" visible={this.state.visibleStatusAlert} onOk={this.onConfirmStatus.bind(this)} onCancel={()=>{this.setState({visibleStatusAlert: false})}}>
                  {this.state.modalInfo}
              </Modal>
          </div>
      )
    }
}

export default carouselManage;
